// pages/release/wantBuy/wantBuy.js
const app = getApp();
Page({

    /**
     * 页面的初始数据
     */
    data: {
        buyId:'',
        userInfo:{},
        publishCar:{
            expectedPrice: '',//期望价格(单位：万元)
            describes: '', //求购信息
            province: '请选择',city:'',district:'',//省市区
            picList:[],//车辆图片
            label:'',
            imageList:[],
        },
        labelList:['定金在手','价格好说','合作卖车','仅限同城'],
    },

    /**
     * 生命周期函数--监听页面加载
     */
    doNothing(){},
onLoad: function (options) {
        // 必须一个ID
        if(undefined != options.bid){
            let self = this;
            this.setData({
                'buyId': options.bid
            },()=>{
                self.InitUserStatus();
            })
        }else{
            app.showNoAuthOrNoGrant('未找到您要查看的求购哦~');
        }
    },
    
    // 检查一下登录状态。
    async InitUserStatus(){
        app.showLoading("获取用户信息");
        await app.checkToken();
        this.InitUserInfo();
        wx.hideLoading();
    },
    InitUserInfo(){
        let userInfo = app.globalData.userInfo;
        // 这里再验证一遍权限。
        if (userInfo.roleList.indexOf('manageWantBuy') == -1) {
            app.showNoAuthOrNoGrant('您无权操作查看此页面');
            return;
        }else{
            this.setData({
                'userInfo': userInfo
            })
            this.wantBuySelfDetail();
        }
    },
    wantBuySelfDetail(){
        app.sHttp.wantBuySelfDetail(this.data.buyId).then(res =>{
            res.result.imageList = [];
            if (undefined != res.result.picList) {
                res.result.picList.forEach(item =>{
                    res.result.imageList.push(item.picUrl);
                })
            }
            this.setData({
                'publishCar': res.result
            });
            this.validSubParams();
        },err=>{
            app.error(err.msg);
        })
    },
    publishCarInput(e){
        let publishCar = this.data.publishCar;
        publishCar[e.currentTarget.dataset.name] = e.detail.value;
        this.setData({
            'publishCar':publishCar
        });
        this.validSubParams();
    },
    changeIcon(e){
        this.setData({
            'publishCar.label': e.currentTarget.dataset.item
        })
    },
    validSubParams(){
        let yuan = {
            expectedPrice: '',//期望价格(单位：万元)
            describes: '', //求购信息
            province: '请选择',city:'',district:'',//省市区
            picList:[],//车辆图片
            label:''
        };
        let publishCar = this.data.publishCar;
        let canSub = true;
        for (const key in publishCar) {
            if (Object.hasOwnProperty.call(publishCar, key) && Object.hasOwnProperty.call(yuan, key)) {
                if ('picList' != key && 'expectedPrice' != key) {
                    if (yuan[key] == publishCar[key]) {
                        canSub = false;
                    }
                }
                
            }
        };
        this.setData({
            'canSub': canSub
        });
        return canSub;
    },
    RegionChange: function(e) {
        this.setData({
            'publishCar.province': e.detail.value[0],
            'publishCar.city': e.detail.value[1],
            'publishCar.district': e.detail.value[2]
        });
        this.validSubParams();
    },
    submitCar(){
        if (this.validSubParams()) {
            // 验证是否上传了图片.
        let self = this;
        let carPicListUpload = this.selectComponent('#imgDrag');
        carPicListUpload.uploadFiles('carArchives',0,true).then(res=>{
            let publishCar = app.deepCopy(self.data.publishCar);
            publishCar.picList = [];
            res.forEach(element => {
                publishCar.picList.push({picUrl: element.originalUrl});
            });
            delete publishCar.createTimeFormat;
            delete publishCar.imageList;
            delete publishCar.status;
            delete publishCar.dealerLogoUrl;
            delete publishCar.dealerName;
            delete publishCar.isAuth;
            delete publishCar.isGoldMedal;
            delete publishCar.userMobile;
            delete publishCar.userName;
            let _this = self;
            app.sHttp.wantBuySelfModify(publishCar).then(res => {
                let _that = _this;
                wx.showModal({
                    title: '发布完成',
                    content: '您的求购发布成功',
                    confirmText:'我知道了',
                    cancelText:'前往查看',
                    showCancel: false,
                    success (res) {
                      if (res.confirm) {
                        _that.BackPage();
                      }
                    }
                })
            },err =>{
                app.error(err.msg);
            })
        },err=>{
          app.error(err.msg);
        });
        }else{
            app.alert('请填写完整信息后发布');
        }
    },
    BackPage() {
      var that = this;
      wx.navigateBack({
        delta: 1,
        fail: function(){
          that.toHome();
        }
      });
    },
    toHome(){
      wx.reLaunch({
        url: '/pages/home/home',
      })
    },
})